package com.bdqn.mr.combine;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context)
            throws IOException, InterruptedException {
        // shuffle:会经历一个shuffle（洗牌）的过程
        // <"love",1> <"love",1> <"love",1>
        // key: "love"
        // values: [IntWritable(1), IntWritable(1), IntWritable(1)]

        // 输出数据的结果：<"love",3>
        int sum = 0;
//        Iterator<IntWritable> iterator = values.iterator();
//        while (iterator.hasNext()) {
//            IntWritable next = iterator.next();
//            int cnt = next.get();
//            sum += cnt;
//        }
        for (IntWritable value : values) {
            sum += value.get();
        }

        total.set(sum);
        context.write(key, total);
    }
    // 代码优化，避免内存中出现太多的对象
    IntWritable total = new IntWritable();
}
